import { Injectable, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import * as moment from 'moment';
import { Http } from '@angular/http';
import {appReportUrl} from '../report/report.url';
import {RemoveTableService} from '../public/serve/remove-table/remove-table.service';
import {HintsService} from '../public/serve/hints/hints.service';
import {SelectItem} from '../public/common/selectitem';

import { ConfigService} from '../public/common/config';

declare var $: any;


//export const Ip= '192.168.0.171:8080';

//export const Ip = '192.168.0.171:8080';

// export const Ip = '192.168.0.171:8080';

//export const Ip= '47.107.47.180:8080';
//export const Ip= '192.168.0.188:8080';



@Injectable()
export class Service {

  public zsurl: any;//访问url
  public baseUrl: string;
  public prompt: any;//提示语
  public promptclose: any;//关闭提示
  public username: string;//登录用户昵称
  public realName: string;//登录用户名
  public right: any = {};//权限
  public createUserId: any;//操作用户
  public portrait: any;
  public websites: any;//门户信息
  public institution: any;//机构信息
  public institutionMolde: boolean;//机构窗口
  public counts: number = 0;
  public eventEmit: any;//定义发射事件
  public addtr: any;
  public ip: any;//ip
  public exitMaxTime: any;
  public exitTime: any;

  public selection: any//滑动块状态
  public headTitle: string = '合同订单';

  public effecteventEmit: any;//功能发射事件
  public effectIdeventEmit: any;//功能id
  public effectsearcheventEmit: any;//功能发射查询
  public institutioneventEmit: any;//机构发射事件
  public institutionsearcheventEmit: any;//机构查询
  public institutionbtneventEmit: any;//机构btn
  public institutiontwoeventEmit: any;//机构第二次窗口状态
  public institutiontreeidnameeventEmit: any;//机构tree数据
  public institutionofeventEmit: any//所辖用户
  public managementeventEmit: any;//用户发射事件
  public passwordeventEmit: any;//重置密码
  public managementUpdateeventEmit: any;//用户发射事件
  public managementroleeeventEmit: any;//用户角色事件
  public managementsearcheventEmit: any;//用户查询
  public managementtreeidnameeventEmit: any;//用户tree数据
  public managementtheeventEmit: any//所属机构
  public disableaddeventEmit: any;//禁用新增发射
  public rolesdataeeventEmit: any;//角色组信息发射
  public rolebyeventEmit: any; //角色关联发射事件
  public rolebylefteventEmit: any;//user
  public rolebyrighteventEmit: any;//关联
  public rolecleareventEmit: any;//角色查询清空

  public perdetailseventEmit: any;//期刊详情
  public perupdateeventEmit: any;//期刊修改
  public perresourceeventEmit: any;
  public perTreeeventEmit: any;//期刊树形数据
  public pertereventEmit: any;//期刊终端下拉
  public perterevAddentEmit: any;//期刊终端添加
  public persareventEmit: any;//期刊搜索数据发射
  public perstatseventEmit: any;//期刊搜索状态发射
  public themeSeventEmit:any;   //主题词搜索状态发射
  public themeTableSeventEmit:any;////主题词表搜索状态发射
  public perpaginationaeventEmit: any;//期刊分页状态发射

  public bookdetailseventEmit: any;//图书详情发射
  public bookupdateeventEmit: any;//图书修改发射
  public booktereventEmit: any;//图书终端发射
  public booksearcheventEmit: any;//图书搜索发射

  public privilegeeventEmit: any;//权限查询

  public journaldeletethreeentEmit: any;//日志删除三个月前
  public journaldeletealleventEmit: any;
  public journaldetailseventEmit: any; //日志删除全部
  public journalsearcheventEmit: any;//日志查询

  public roleeventEmit: any;//角色查询
  public roleseventEmit: any;//角色组查询

  public taskdetailseventEmit: any;//任务详情
  public databasedetailseventEmit: any;//数据库详情
  public databaseupdateeventEmit: any;//数据库详情
  public tasksearcheventEmit: any;//任务查询

  public homeusereventEmit: any;//
  public homeinstitutioneventEmit: any;//首页快捷入口新增用户
  public homebrancheventEmit: any;//首页快捷入口新增用户
  public homeinstitutionaleventEmit: any;//首页快捷入口新增用户
  public pavmenutreeeventEmit: any;//栏目树形发射
  public refresheventEmit: any;//更改信息后刷新
  public resourceclassifyeventEmit: any;//资源分类active
  public resmoveeventEmit: any;//资源分类移动
  public resclickeventEmit: any;//资源分类点击选中数据
  public menutreeideventEmit: any;//栏目管理树形id
  public menumoveeventEmit: any;//栏目移动
  public brancheventEmit: any;//分管添加
  public videoResourceEmt: EventEmitter<string>;

  public websiteseventEmit: any//logo
  public usernameeventEmit: any//昵称
  public userportraiteventEmit: any;//头像
  public righteventEmit: any;//权限
  public selectioneventEmit: any//滑动块

  public taskProjectEmit: any;//新增任务关联产品
  public producttypedetailseventEmit: any//产品分类详情
  public producttypesearchseventEmit: any//产品搜索

  public leftsynonyminitdataeventEmit: any//同义词

  public internalindexeddeleteentEmit: any;
  public internalLeftIndexingDeleteEmit:any;

  public internalindexedmodelreldeleteentEmit: any;

  public onSubmitAppViewEmit: any;
  public onParentKeyworkTabListEmit: any;

  public onKeyworkTabListEmit: any;//主题词
  public internalIndexedRelThemeEmit: any;//相关主题词
  public onExportKeyworkEmit: any;//主题词
  public onDownloadKeyworkEmit:any;//下载主题词
  public onProductTimeMetaEmit: any;//时间属性列表
  public onExportKeyworkTableEmit: any;//主题词表导出

  public internalThemeWordsLeftEmit: any;//主题词左侧
  public internalThemeWordsTablesRelEmit: any;//主题词关联列表

  public referenceInternalThemeWordsLeftEmit: any;//参考标引主题词左侧
  public referenceInternalThemeWordsTablesRelEmit: any;//参考标引主题词关联列表
  public internalThemeInternalAttributeEmit: any;//主题词左侧关联属性
  public referenceThemeInternalAttributeEmit: any;//参考标引主题词左侧关联属性

  public internalRightClickMenuEmit: any;//右键标引modal传值
  public internalRightModalEmit: any;//右键标引auto传值
  public internalTimeAttributeEmit:any;//时间属性
  public internalDeleteContentsEmit: any;//删除内文标引回调
  public internalDeleteThemeIdEmit: any;//删除内文标引回调
  public internalDeleteTimeAttributeContentContentsEmit:any;//删除内文时间属性
  public closeCurrentPageEimt:any;

  public messageOrder = new EventEmitter();
  public messageStorage = new EventEmitter();
  public messageContract = new EventEmitter();

  public priceEmit = new EventEmitter();
  public sitedeleteeventEmit: any;//站点删除
  public sitetypeeventEmit: any;//站点状态
  public sitemanageeventEmit: any;//管理端删除状态
  public sitegatewayeventEmit: any;//门户端删除状态
  public ordereventEmit: any;//订单导航
  public contracteventEmit: any;//合同导航
  public videoEmit: any;//视频名字
  public eixtTimeEmit: any;//定时退出
  public loadingStorage: boolean = false;
  public loadingTitle: any = '';
  public prevent: boolean = false;
  constructor(private http: Http,private configService : ConfigService) {
    this.ip = configService.HttpUrl;
    this.zsurl = 'http://' + this.ip;
    this.baseUrl = this.zsurl + configService.BaseName;
    this.prompt = { prompt: false, success: false, fail: false, promptStatement: '' };
    this.promptclose = setInterval(() => {
      this.prompt = { prompt: false }
      //window.clearInterval(this.prompt);
    }, 3000)


    this.username = '';
    //this.right = {};
    this.eventEmit = new EventEmitter();
    this.effecteventEmit = new EventEmitter();
    this.institutioneventEmit = new EventEmitter();
    this.institutionsearcheventEmit = new EventEmitter();
    this.institutionbtneventEmit = new EventEmitter();
    this.institutiontwoeventEmit = new EventEmitter();
    this.institutiontreeidnameeventEmit = new EventEmitter();
    this.institutionofeventEmit = new EventEmitter();
    this.managementeventEmit = new EventEmitter();
    this.managementUpdateeventEmit = new EventEmitter();
    this.managementroleeeventEmit = new EventEmitter();
    this.managementsearcheventEmit = new EventEmitter();
    this.managementtreeidnameeventEmit = new EventEmitter();
    this.managementtheeventEmit = new EventEmitter();
    this.disableaddeventEmit = new EventEmitter();
    this.passwordeventEmit = new EventEmitter();
    this.rolesdataeeventEmit = new EventEmitter();
    this.rolebyeventEmit = new EventEmitter();
    this.rolebylefteventEmit = new EventEmitter();
    this.rolebyrighteventEmit = new EventEmitter();
    this.rolecleareventEmit = new EventEmitter();

    this.perdetailseventEmit = new EventEmitter();
    this.perTreeeventEmit = new EventEmitter();
    this.pertereventEmit = new EventEmitter();
    this.perterevAddentEmit = new EventEmitter();
    this.perupdateeventEmit = new EventEmitter();
    this.perresourceeventEmit = new EventEmitter();
    this.persareventEmit = new EventEmitter();
    this.perstatseventEmit = new EventEmitter();
    this.themeSeventEmit = new EventEmitter();
    this.themeTableSeventEmit = new EventEmitter();
    this.perpaginationaeventEmit = new EventEmitter();

    this.bookdetailseventEmit = new EventEmitter();
    this.bookupdateeventEmit = new EventEmitter();
    this.booktereventEmit = new EventEmitter();
    this.booksearcheventEmit = new EventEmitter();
    this.effectIdeventEmit = new EventEmitter();
    this.effectsearcheventEmit = new EventEmitter();

    this.privilegeeventEmit = new EventEmitter();
    this.journaldeletethreeentEmit = new EventEmitter();
    this.journaldetailseventEmit = new EventEmitter();
    this.journalsearcheventEmit = new EventEmitter();
    this.roleeventEmit = new EventEmitter();
    this.roleseventEmit = new EventEmitter();
    this.taskdetailseventEmit = new EventEmitter();
    this.databasedetailseventEmit = new EventEmitter();
    this.databaseupdateeventEmit = new EventEmitter();
    this.tasksearcheventEmit = new EventEmitter();
    //首页快捷入口发射
    this.homeusereventEmit = new EventEmitter();
    this.homeinstitutioneventEmit = new EventEmitter();
    this.homebrancheventEmit = new EventEmitter();
    this.homeinstitutionaleventEmit = new EventEmitter();
    //栏目树形数据
    this.refresheventEmit = new EventEmitter();
    //资源分类active
    this.resourceclassifyeventEmit = new EventEmitter();
    this.resmoveeventEmit = new EventEmitter();
    this.resclickeventEmit = new EventEmitter();
    this.menutreeideventEmit = new EventEmitter();
    this.menumoveeventEmit = new EventEmitter();
    this.videoResourceEmt = new EventEmitter();
    //日志管理
    this.journaldeletethreeentEmit = new EventEmitter();
    this.journaldeletealleventEmit = new EventEmitter();
    this.websiteseventEmit = new EventEmitter();
    this.usernameeventEmit = new EventEmitter();
    this.userportraiteventEmit = new EventEmitter();
    this.righteventEmit = new EventEmitter();
    this.selectioneventEmit = new EventEmitter();

    this.taskProjectEmit = new EventEmitter();

    //产品分类管理
    this.producttypedetailseventEmit = new EventEmitter();
    this.producttypesearchseventEmit = new EventEmitter();

    //同义词
    this.leftsynonyminitdataeventEmit = new EventEmitter();
    //内文标引主题词删除索引
    this.internalindexeddeleteentEmit = new EventEmitter();
    this.internalLeftIndexingDeleteEmit = new EventEmitter();
    //相关主题词删除
    this.internalindexedmodelreldeleteentEmit = new EventEmitter();

    this.onSubmitAppViewEmit = new EventEmitter();
    this.onParentKeyworkTabListEmit = new EventEmitter();

    this.onKeyworkTabListEmit = new EventEmitter();
    this.internalIndexedRelThemeEmit = new EventEmitter();
    this.onExportKeyworkEmit = new EventEmitter();
    this.onDownloadKeyworkEmit = new EventEmitter();
    this.onExportKeyworkTableEmit = new EventEmitter();
    this.internalThemeWordsLeftEmit = new EventEmitter();
    this.internalThemeWordsTablesRelEmit = new EventEmitter();
    this.referenceInternalThemeWordsLeftEmit = new EventEmitter();
    this.referenceInternalThemeWordsTablesRelEmit = new EventEmitter();
    this.internalThemeInternalAttributeEmit = new EventEmitter();
    this.referenceThemeInternalAttributeEmit = new EventEmitter();
    this.internalRightClickMenuEmit = new EventEmitter();
    this.internalRightModalEmit = new EventEmitter();
    this.internalTimeAttributeEmit = new EventEmitter();
    this.internalDeleteContentsEmit = new EventEmitter();
    this.internalDeleteThemeIdEmit = new EventEmitter();
    this.onProductTimeMetaEmit = new EventEmitter();
    this.internalDeleteTimeAttributeContentContentsEmit = new EventEmitter();
    this.closeCurrentPageEimt = new EventEmitter();

    //站点管理
    this.sitedeleteeventEmit = new EventEmitter();
    this.sitetypeeventEmit = new EventEmitter();
    this.sitemanageeventEmit = new EventEmitter();
    this.sitegatewayeventEmit = new EventEmitter();
    //分管
    this.brancheventEmit = new EventEmitter();
    this.videoEmit = new EventEmitter();
    //订单
    this.ordereventEmit = new EventEmitter();
    this.contracteventEmit = new EventEmitter();
    this.eixtTimeEmit = new EventEmitter();

    //接受查询结果
    this.selectioneventEmit.subscribe((value: any) => {
      this.selection = value;
    });
    //设置退出时长（秒钟）
    this.exitMaxTime = 1800;
  }


  //存取权限
  public getRight() {
    return JSON.parse(sessionStorage.getItem('user-rights'));
  }

  public setRight(value) {
    sessionStorage.setItem('user-rights', JSON.stringify(this.right));

  }

  //存取用户Id
  public getuser() {
    return sessionStorage.getItem('user');
  }

  public setuser(value) {
    sessionStorage.setItem('user', this.createUserId);
  }

  //存取用户昵称
  public getuserName() {
    return sessionStorage.getItem('username');
  }
  public setuserName(value) {
    sessionStorage.setItem('username', this.username);
  }
  //存取用户名
  public getRealName() {
    return sessionStorage.getItem('realName');
  }
  public setRealName(value) {
    sessionStorage.setItem('realName', this.realName);
  }

  //存取头像
  public getuserPortrait() {
    return sessionStorage.getItem('portrait');
  }
  public setuserPortrait(value) {
    sessionStorage.setItem('portrait', this.portrait);
  }

  //存取门户
  public getwebsites() {
    return JSON.parse(sessionStorage.getItem('websites'));
  }
  public setwebsites(value) {
    sessionStorage.setItem('websites', JSON.stringify(this.websites));
  }

  //存取门户
  public getInstitution() {
    return JSON.parse(sessionStorage.getItem('institution'));
  }
  public setInstitution(value) {
    sessionStorage.setItem('institution', JSON.stringify(this.institution));
  }

  //存取消息个数
  public getcounts() {
    return JSON.parse(sessionStorage.getItem('counts'));
  }
  public setcounts(value) {
    sessionStorage.setItem('counts', value);
  }

  //存取新建订单个数
  public getOrdercounts() {
    return JSON.parse(sessionStorage.getItem('addOrderNumberArray'));
  }
  public setOrdercounts(value) {
    sessionStorage.setItem('addOrderNumberArray', JSON.stringify(value));
  }




  public isActive = true;
  //isActive: EventEmitter<boolean>;
  indent() {
    this.isActive = !this.isActive;
    return this.isActive;
  }

  /**
   * 冒泡排序   
   * @param arr 排序的数组
   * @param key 根据的key排序
   * @param direction 排序的方向
   */
  public bubbleSort(arr: Array<any>, key?: string, direction?: -1 | 1) {
    key = key ? key : null
    direction = direction ? direction : 1
    for (let i = 0; i < arr.length - 1; i++) {
      for (let j = 0; j < arr.length - i - 1; j++) {

        if (key) {
          let compare = Number(arr[j][key]) - Number(arr[j + 1][key])
          if (compare > 0) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
          }
        } else {
          let compare = Number(arr[j]) - Number(arr[j + 1])
          if (compare > 0) {
            [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
          }
        }
      }
    }
  }
  //转换时间格式
  formatDate(now) {
    var a = /^(\d{4})-(\d{2})-(\d{2})$/
    if (!a.test(now) && now != '' && now != null) {
      var year = now.getFullYear() || '';
      var month = now.getMonth() + 1 || '';
      month = ("0" + (now.getMonth() + 1)).slice(-2);
      var date = now.getDate() || '';
      date = ("0" + (now.getDate())).slice(-2);
      var hour = now.getHours() || '';
      var minute = now.getMinutes() || '';
      var second = now.getSeconds() || '';
      //return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second || '';
      //不要时分秒
      return year + "-" + month + "-" + date;
    } else {
      return now || '';
    }
  }
  //时间搓转时间格式
  fmtDate(obj) {
    if (obj) {
      var date = new Date(obj);
      var y = date.getFullYear();
      var m = "0" + (date.getMonth() + 1);
      var d = "0" + date.getDate();
      return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
    } else {
      return '';
    }
  }

  public closeindentbutton() {
    this.isActive = false;
    this.eventEmit.emit(this.isActive);
  }
  // public openWindow(url){  
  //   var newWin = window.open('about:blank');
  //   let link = document.createElement('a');  
  //   link.target = "_blank";  
  //   link.href = url;  
  //      document.body.appendChild(link);  
  //   link.click();  
  //   document.body.removeChild(link)
  // } 
  public openWindow(url) {
    var link = document.createElement('a');
    link.href = url;
    link.download = "contractScansFile";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  public openWindowA(url) {
    let filename = url.substring(url.lastIndexOf("/")+1);
    let link = document.createElement('a');
    link.target = "_blank";
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    //document.body.removeChild(link);
  }

  public openWindowB(xmlUrl){
    let filename = xmlUrl.substring(xmlUrl.lastIndexOf("/")+1);
    let link = document.createElement('a');
    link.href = xmlUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  public openWindowXML(xmlUrl){
    let filename = xmlUrl.substring(xmlUrl.lastIndexOf("/")+1);
    var xhr = new XMLHttpRequest();
    xhr.open('GET', xmlUrl, true);//get请求，请求地址，是否异步
    xhr.responseType = "blob";    // 返回类型blob
    xhr.onload = function () {// 请求完成处理函数
      if (this.status === 200) {
        var blob = this.response;// 获取返回值
        var link = document.createElement('a');
        link.download = filename;
        link.href=window.URL.createObjectURL(blob);
        link.click();
        }
    };
    // 发送ajax请求
    xhr.send();
  }

  public download(xmlUrl) {
    let text = this._xmlOfHtml(xmlUrl);
    if(text != ''){
      let filename = xmlUrl.substring(xmlUrl.lastIndexOf("/")+1);
      let element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);
      element.style.display = 'none';
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    }
  }

  //获取xml文件中的内容
  _xmlOfHtml(xml_path){
    let text = '';
    $.ajax({ 
      type : "POST", 
      url : xml_path, 
      async : false, 
      dataType:'xml',
      success : function(data){ 
        text = data;
      } 
    }); 
    return text;
  }

  //判断url是否存在
  _fileExists(url){
    let isExists;
    $.ajax({
      url:url,
      async:false,
      type:'HEAD',
      error:function(){
        isExists = 0;
      },success:function(){
        isExists = 1;
      }
    })

    if(isExists == 1){
      return true;
    }else{
      return false;
    }
  }


  //模态框动态居中
  public modalHeightAuto() {
    let showModal = $('.modal-open .modal-dialog .modal-content').toArray().filter(dom => dom.offsetHeight > 20);
    let height = (showModal.length) ? showModal[0].offsetHeight : 0;
    let top = ($(window).height() - height) / 2;
    //console.log($(window).height(),height,top)
    if (height != 0) {
      $('.modal-dialog').animate({ "margin-top": top + "px", "margin-bottom": top + "px" });
    }

  }

  //延时模态框动态居中
  public setTimeoutModalHeightAuto() {
    setTimeout(() => {
      this.modalHeightAuto();
    }, 300);
  }

  //时间控件转换提交时间
  toDate(date) {
    let result = moment(date).format("YYYY-MM-DD")
    if (result == 'Invalid date' || result == "1970-1-1") {
      return "";
    }
    return result
  }

  //超时退出
  public intervalId: any;
  public automatic: boolean = false;
  public openTime(maxtime) {
    clearInterval(this.intervalId);
    this.exitTime = maxtime;
    this.intervalId = setInterval(() => {
      this.exitTime--;
      // console.log(this.exitTime)
      if (this.exitTime == 10) {
        this.eixtTimeEmit.emit(10);
        $(".modal").modal("hide");
      }
      if (this.exitTime <= 0) {
        clearInterval(this.intervalId);
        this.automatic = false;

        this.eixtTimeEmit.emit(0);
      }
    }, 1000)
  }
  public ShowInvalidLoginMessage() {
    //alert("您已经长时间没操作了，即将退出系统");
    this.eixtTimeEmit.emit();
  }

  //输入保留两位小数
  public clearNoNum(obj) {
    console.log(obj)
    if (obj) {
      obj = obj.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符   
      obj = obj.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
      //obj = obj.replace(!/^[1-9]\d*(\.\d+)?$/);//不能输入0 
      obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数   !
      if (obj.indexOf(".") < 0 && obj != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
        obj = parseFloat(obj);
      }
      if (obj == 0) {
        return '';
      }
      return obj;
    }
    return '';
  }
  //结果保留两位小数
  parseFloat(val) {
    if (val) {
      return parseFloat(val).toFixed(2);
    }
    return '0.00';
  }

  //输入保留两位小数
  public clearNoNumTwo(obj) {
    console.log(obj)
    if (obj) {
      obj = obj.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符   
      obj = obj.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
      //obj = obj.replace(!/^[1-9]\d*(\.\d+)?$/);//不能输入0 
      obj = obj.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数   !
      if (obj.indexOf(".") < 0 && obj != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
        obj = parseFloat(obj);
      }
      return obj;
    }
    return '';
  }
}
